import javax.swing.tree.TreeNode;

public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode (int val){
            this.val=val;
        }
    }

    public TreeNode root=null;
    public TreeNode search(int key){
        TreeNode cur=root;
        while(cur!=null){
            if(cur.val<key){
                cur=cur.right;
            }else if(cur.val>key){
                cur=cur.left;
            }else{
                return cur;
            }
        }
        return null;
    }

    public void insert(int val){
        //创建新节点
        TreeNode node=new TreeNode(val);
        if(root==null){
            //树为空时,新节点就是根节点
            root=node;
            return;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val<val){
                parent=cur;
                cur=cur.right;
            }else if(cur.val>val){
                parent=cur;
                cur=cur.left;
            }else{
                return;
            }
        }
        //parent 指向的节点,就是需要插入的节点位置 的 父亲节点
        if(parent.val>val){
            parent.left=node;
        }else{
            parent.right=node;
        }

    }
}
